package com.suxin.reactor;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * @author Tang
 * @classname Handler
 * @description [  ]
 * @date 2021/2/2 20:34
 */
public class Handler implements Runnable{

    private SocketChannel socketChannel;
    private SelectionKey sk;
    ByteBuffer input = ByteBuffer.allocate(1024);
    ByteBuffer output = ByteBuffer.allocate(1024);
    static final int READING = 0, SENDING = 1;
    int state = READING;

    public Handler(Selector selector,SocketChannel socketChannel) throws Exception {
        this.socketChannel = socketChannel;
        socketChannel.configureBlocking(false);
        // 此处的0，表示不关注任何事件
        sk = this.socketChannel.register(selector, 0);
        sk.attach(this);
        sk.interestOps(SelectionKey.OP_READ);
        selector.wakeup();
    }

    boolean inputIsComplete() {
        return true;
    }

    boolean outputIsComplete() {
        return true;
    }

    void process() {
        System.out.println("process...");
    }

    @Override
    public void run() {
        if (state == READING) {
            read();
        } else if (state == SENDING) {
            send();
        }
    }

    private void send() {
        try {
            socketChannel.read(input);
            if (inputIsComplete()) {
                process();
                state = SENDING;
                sk.interestOps(SelectionKey.OP_WRITE);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void read() {
        try {
            socketChannel.write(output);
            if (outputIsComplete()) {
                // 已注销的建
                sk.cancel();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}